package com.iplatform.iplatformuser.function.group.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iplatform.commons.SpringUtil;
import com.iplatform.iplatformuser.common.CollectionUtil;
import com.iplatform.iplatformuser.common.ConstantUtil;
import com.iplatform.iplatformuser.framework.util.UniqueIDGenerator;
import com.iplatform.module.privilege.group.*;
import com.iplatform.iplatformuser.function.group.dao.PriGroupMapper;
import com.iplatform.iplatformuser.function.group.service.inter.IPriGroupService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 *
 * @author yb
 *
 */
@Service
public class PriGroupServiceImpl implements IPriGroupService{

	@Autowired
	private PriGroupMapper mapper;

	@Override
	public List<PriGroupInfoBean> queryGroupInfo() {
		return mapper.queryGroupInfo();
	}

	@Transactional
	public Integer deleteGroupById(String id) {
		return mapper.deleteGroupById(id);
	}

	@Transactional
	public int updateGroup(Map<String, String> formMap) {
		return mapper.updateGroup(formMap);
	}

	@Override
	public List<PriGroupInfoBean> queryGroup(Map<String, String> formMap) {
		return mapper.queryGroup(formMap);
	}

	@Transactional
	public int insertGroup(Map<String, String> formMap) {
		return mapper.insertGroup(formMap);
	}

	@Transactional
	public void batchDeleteGroup(String[] deleteIds) {
		mapper.batchDeleteGroup(deleteIds);
	}

	@Override
	public List<PriGroupInfoBean> queryGroupByName(Map<String, String> formMap) {
		return mapper.queryGroupByName(formMap);
	}

	@Override
	public String queryMaxOrderNo() {
		return mapper.queryMaxOrderNo();
	}


	@Override
	public List<Map<String, String>> listSelectWithOutResource(Map<String, String> formMap) {
		return mapper.listSelectWithOutResource(formMap);
	}

	@Override
	public List<Map<String, String>> listSelectWithInResource(Map<String, String> formMap) {
		return mapper.listSelectWithInResource(formMap);
	}

	@Override
    public List<String> queryUseSpecByUserId(String userId) {
        return mapper.queryUseSpecByUserId(userId);
    }

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public void updateGroupResource(Map<String, String> formMap) {

		String checkedIds = formMap.get("checkedIds");
		//再同步资源到角色处
		String[] split = checkedIds.split(",");
		//最新选择的资源列表
		List<String> selectedList = new ArrayList(Arrays.asList(split));
		//跟权限组绑定的资源列表
		List<String> resList = mapper.queryResourceByGroupId(formMap);
		//跟权限组绑定的所有中间件
		List<String> mediumList = mapper.queryMediumByGroupId(formMap);
		//通过比较找出新增的
		List<String> addList = SpringUtil.compare(resList, selectedList);
		//通过比较找出删除的
		List<String> subList = SpringUtil.compare(selectedList, resList);
		//每个绑定这个权限组的中间件都要更新一下，新增的增加
		for(String mediumId : mediumList) {
			for(String resourceId : addList) {
				Map<String, String> map = CollectionUtil.getHashMap(4);
				map.put("resourceId", resourceId);
				map.put("groupId", formMap.get("groupId"));
				map.put("mediumType", ConstantUtil.ROLE);
				map.put("mediumId", mediumId);
				mapper.insertMediumResource(map);
			}
		}
		//减少的删除
		for(String mediumId : mediumList) {
			for(String resourceId : subList) {
				Map<String, String> map = CollectionUtil.getHashMap(4);
				map.put("resourceId", resourceId);
				map.put("groupId", formMap.get("groupId"));
				map.put("mediumType", ConstantUtil.ROLE);
				map.put("mediumId", mediumId);
				mapper.delMediumResource(map);
			}
		}

		//先删除原来绑定的资源
		mapper.delWithGroupId(formMap);
		//再新增新的资源
		if (!StringUtils.isEmpty(checkedIds)) {
			for (String resourceId : checkedIds.split(",")) {
				Map<String, String> map = CollectionUtil.getHashMap(2);
				map.put("groupId", formMap.get("groupId"));
				map.put("resourceId", resourceId);
				mapper.updateGroupResource(map);
			}
		}

	}

	@Override
	public List<Map<String, String>> queryInBindRoleList(Map<String, String> formMap) {
		return mapper.queryInBindRoleList(formMap);
	}

	@Override
	public List<Map<String, String>> queryOutBindRoleList(Map<String, String> formMap) {
		return mapper.queryOutBindRoleList(formMap);
	}

	@Transactional
	public void insertGroupMeduim(Map<String, String> formMap) {
		//根据groupId删除关系
		Map<String, String> delMap = CollectionUtil.getHashMap(2);
		delMap.put("groupId", formMap.get("groupId"));
		delMap.put("mediumType", formMap.get("mediumType"));
		mapper.delGroupMedium(delMap);

		if(!StringUtils.isEmpty(formMap.get("checkedIds"))) {
			for(String checkId : formMap.get("checkedIds").split(",")) {
				Map<String, String> map = CollectionUtil.getHashMap(2);
				map.put("groupId", formMap.get("groupId"));
				map.put("mediumId", checkId);
				map.put("mediumType", formMap.get("mediumType"));
				//增加权限组中间件绑定
				mapper.insertGroupMedium(map);
				//先删除原来中间件绑定的资源
				mapper.delMediumResource(map);
				//同时需要同步权限组这边的资源过去
				mapper.sysResGroupToMedium(map);
			}
		}
	}

	@Transactional
	public void insertMediumGroup(Map<String, String> formMap) {
		//根据mediumId删除关系
		Map<String, String> delMap = CollectionUtil.getHashMap(2);
		delMap.put("mediumId", formMap.get("mediumId"));
		delMap.put("mediumType", formMap.get("mediumType"));
		mapper.delGroupMedium(delMap);

		if(!StringUtils.isEmpty(formMap.get("groupIds"))) {
			for(String groupId : formMap.get("groupIds").split(",")) {
				Map<String, String> map = CollectionUtil.getHashMap(3);
				map.put("groupId", groupId);
				map.put("mediumId", formMap.get("mediumId"));
				map.put("mediumType", formMap.get("mediumType"));
				//增加权限组中间件绑定关系
				mapper.insertGroupMedium(map);
				//先删除原来中间件绑定的资源
				mapper.delMediumResource(map);
				//同时需要同步权限组这边的资源过去
				mapper.sysResGroupToMedium(map);
			}
		}
	}

	@Override
	public List<PriResourcesTree> queryMenuTreeByGroupId(
			Map<String, String> formMap) {
		return mapper.queryMenuTreeByGroupId(formMap);
	}

	@Transactional
	public void insertGroupOpt(Map<String, String> formMap) {
		String groupId = formMap.get("groupId");
		String checkIds = formMap.get("checkedIds");
		String createBy = formMap.get("createBy");

		//删除此权限组的所有绑定
		mapper.delGroupOptByGroupId(groupId);

		//再增加新的绑定
		List<Map<String, String>> mapList = new ArrayList<>();
		if(!StringUtils.isEmpty(checkIds)) {
			for(String checkId : checkIds.split(",")) {
				Map<String, String> map = CollectionUtil.getHashMap(2);
				map.put("groupId", groupId);
				map.put("resOptId", checkId);
				map.put("createBy", createBy);
				mapList.add(map);
			}
			mapper.insertGroupOpt(mapList);
		}


	}

	@Override
	public List<PriResourcesTree> querySpecTreeByGroupId(Map<String, String> formMap) {

		return mapper.querySpecTreeByGroupId(formMap);
	}

	@Override
	public List<HashMap<String, String>> queryGroupName() {
		return mapper.queryGroupName();
	}

	@Override
	public List<PriResourcesTree> queryTargetByGroupId(Map<String, String> formMap) {
		return mapper.queryTargetByGroupId(formMap);
	}

	@Override
	public List<DataSetCategory> queryDataSet(Map<String, String> formMap) {
		return mapper.queryDataSet(formMap);
	}

	@Override
    public List<String> queryDataSetIdByGroup(String userId) {
	  return mapper.queryDataSetIdByGroup(userId);
    }

    @Override
    public List<String> queryDataSetColIdByGroup(String userId, String dataSetId) {
      return mapper.queryDataSetColIdByGroup(userId, dataSetId);
    }

    @Override
    public List<String> queryDataSetColAliasByGroup(String userId, String dataSetId) {
      return mapper.queryDataSetColAliasByGroup(userId, dataSetId);
    }

    @Override
    public List<String> queryUseSpecNameByUserId(String userId) {
      return mapper.queryUseSpecNameByUserId(userId);
    }

    @Override
    public List<String> queryUseOrgByUserId(String userId) {
      return mapper.queryUseOrgByUserId(userId);
    }

    @Override
    public List<String> queryUseManagerOrgByUserId(String userId) {
    	return mapper.queryUseManagerOrgByUserId(userId);
    }

  @Transactional
	public void addGroupDataSet(String groupDataSetJson) {
		JSONObject object = JSON.parseObject(groupDataSetJson);
		String groupId = object.getString("groupId");
		JSONArray jsonArray = object.getJSONArray("groupSet");

		mapper.deleteGroupDataSetByGroupId(groupId);

		List<Map<String, String>> groupSetMapList = new ArrayList<>();
		if(!CollectionUtils.isEmpty(jsonArray)) {
			for(int i=0; i<jsonArray.size(); i++) {
				Map<String, String> map = CollectionUtil.getHashMap(3);
				JSONObject setObject = JSON.parseObject(jsonArray.getString(i));
				map.put("groupId", groupId);
				map.put("setId", setObject.getString("setId"));
				map.put("useType", setObject.getString("useType"));
				map.put("manageType", setObject.getString("manageType"));
				groupSetMapList.add(map);
			}
			mapper.addGroupDataSet(groupSetMapList);
		}
	}

	@Override
	public List<DataSetColumn> queryColumnByGroupIdAndSetId(Map<String, String> formMap) {
		return mapper.queryColumnByGroupIdAndSetId(formMap);
	}

	@Transactional
	public void addGroupSetColumn(Map<String, String> formMap) {
		String groupId = formMap.get("groupId");
		String setId = formMap.get("setId");
		String selectIds = formMap.get("selectIds");

		mapper.deleteGroupSetColumn(formMap);

		List<Map<String, String>> groupSetColumnList = new ArrayList<>();
		if(!StringUtils.isEmpty(selectIds)) {
			for(String columnId : selectIds.split(",")) {
				Map<String, String> map = CollectionUtil.getHashMap(3);
				map.put("groupId", groupId);
				map.put("setId", setId);
				map.put("columnId", columnId);
				groupSetColumnList.add(map);
			}
			mapper.addGroupSetColumn(groupSetColumnList);
		}

	}

	@Override
	public GroupDataSetRow queryRowByGroupIdAndSetId(Map<String, String> formMap) {
		formMap.put("parentId", "0");
		List<GroupDataSetRow> topRowList = mapper.queryRowByGroupIdAndSetId(formMap);
		GroupDataSetRow topRow = null;
		if(!CollectionUtils.isEmpty(topRowList)) {
			topRow = topRowList.get(0);
			formMap.put("parentId", topRow.getId());
			List<GroupDataSetRow> rowList = mapper.queryRowByGroupIdAndSetId(formMap);
			topRow.setRowList(getSonRow(rowList, formMap));
		}
		return topRow;
	}

	private List<GroupDataSetRow> getSonRow(List<GroupDataSetRow> rowList, Map<String, String> formMap){
		for(GroupDataSetRow row : rowList) {
			formMap.put("parentId", row.getId());
			List<GroupDataSetRow> rowSonList = mapper.queryRowByGroupIdAndSetId(formMap);
			row.setRowList(getSonRow(rowSonList, formMap));
		}
		return rowList;
	}

	@Transactional
	public void addGroupDataSetRow(GroupDataSetRow groupDataSetRow) {
		if(!StringUtils.isEmpty(groupDataSetRow.getId())) {
			//先删除
			mapper.delGroupDataSetRow(groupDataSetRow.getId());

			//再新增
			mapper.addGroupDataSetRow(groupDataSetRow);
			addSonRow(groupDataSetRow, groupDataSetRow.getRowList());
		}else {
			groupDataSetRow.setId(UniqueIDGenerator.getUUID());
			groupDataSetRow.setParentId("0");

			//直接新增
			mapper.addGroupDataSetRow(groupDataSetRow);
			addSonRow(groupDataSetRow, groupDataSetRow.getRowList());
		}
	}


	private void addSonRow(GroupDataSetRow groupDataSetRow, List<GroupDataSetRow> rowList){
		if(!CollectionUtils.isEmpty(rowList)) {
			for(GroupDataSetRow row : rowList) {
				if(StringUtils.isEmpty(row.getId())) {
					row.setId(UniqueIDGenerator.getUUID());
					row.setParentId(groupDataSetRow.getId());

					mapper.addGroupDataSetRow(row);
					addSonRow(row, row.getRowList());
				}else {
					mapper.addGroupDataSetRow(row);
					addSonRow(row, row.getRowList());
				}
			}
		}
	}

	@Override
	public List<PriResourcesTree> queryOrgTreeByGroupId(Map<String, String> formMap) {
		return mapper.queryOrgTreeByGroupId(formMap);
	}

	@Override
	public List<PriResourcesTree> queryManagerOrgTreeByGroupId(Map<String, String> formMap) {
		return mapper.queryManagerOrgTreeByGroupId(formMap);
	}

	@Override
	public List<Map<String, String>> queryInBindGroup(Map<String, String> map) {
		return mapper.queryInBindGroup(map);
	}

	@Override
	public List<Map<String, String>> queryOutBindGroup(Map<String, String> map) {
		return mapper.queryOutBindGroup(map);
	}

	@Override
	public List<PriResourcesTree> queryMenuTreeByMediumId(Map<String, String> map) {
		return mapper.queryMenuTreeByMediumId(map);
	}

	@Transactional
	public void updateMediumResource(Map<String, String> formMap) {
		//先删除
		mapper.delMediumResource(formMap);

		//再新增
		String checkedIds = formMap.get("checkedIds");
		if(!StringUtils.isEmpty(checkedIds)) {
			String[] checkedIdsArray = checkedIds.split(",");
			for(String resourceId : checkedIdsArray) {
				Map<String, String> map = CollectionUtil.getHashMap(4);
				map.put("resourceId", resourceId);
				map.put("mediumId", formMap.get("mediumId"));
				map.put("mediumType", formMap.get("mediumType"));
				map.put("groupId", formMap.get("groupId"));
				mapper.insertMediumResource(map);
			}
		}
	}

	@Override
	public List<PriResourcesTree> queryOrgTreeByMediumId(Map<String, String> map) {
		return mapper.queryOrgTreeByMediumId(map);
	}

	@Override
	public List<PriResourcesTree> querySpecTreeByMediumId(Map<String, String> map) {
		return mapper.querySpecTreeByMediumId(map);
	}

	@Override
	public List<PriResourcesTree> queryTargetByMediumId(Map<String, String> map) {
		return mapper.queryTargetByMediumId(map);
	}

}
